package sagroup.util;

import lights.adapters.Field;
import lights.adapters.Tuple;
import lights.interfaces.IField;
import lights.interfaces.ITuple;
import lights.interfaces.IValuedField;

public class Lights {
	public static boolean isWildTemplate(ITuple template) {
		assert template.length() > 0;
		Field field = (Field) (template.get(template.length() - 1));
		if (field.isFormal())
			return false;
		boolean ret = lights.dracots.Field.MATCH_ALL_FIELD.getValue()
				.equals(field.getValue());
		return ret;
	}

	/**
	 * For easy use.
	 * 
	 * @param t
	 * @param index
	 * @return
	 * @author Xing Jiankuan
	 */
	public static Object getFieldValue(ITuple t, int index) {
		assert index < t.length();
		Object ret;
		ret = ((IValuedField) (t.get(index))).getValue();
		return ret;
	}

	public static ITuple creatTuple(Object string) {
		if (string == null) {
			return new Tuple();
		} else if (string instanceof Class) {
			return new Tuple().add(new Field().setType((Class) string));
		} else {
			return new Tuple().add(new Field().setValue(string));
		}
	}

	/**
	 * @param fields
	 * @return
	 * @author Xing Jiankuan
	 */
	public static ITuple creatTuple(Object[] fields) {
		ITuple ret = new Tuple();
		if (fields != null) {
			for (int i = 0; i < fields.length; i++) {
				if (fields[i] instanceof Class) {
					ret.add(new Field().setType((Class) fields[i]));
				} else {
					ret.add(new Field().setValue(fields[i]));
				}
			}
		}
		return ret;
	}

	public static ITuple[] creatTuples(Object[] objects) {
		assert objects != null;
		ITuple[] ret = new ITuple[objects.length];
		for (int i = 0; i < objects.length; i++) {
			ret[i] = creatTuple(objects[i]);
		}
		return ret;
	}

	static public String tupleAllFieldTypeStr(ITuple t) {
		StringBuilder sb = new StringBuilder();
		IField[] fields = t.getFields();
		for (int i = 0; i < fields.length; i++) {
			sb.append(fields[i].getType().getName());
			sb.append("+");
		}
		// logger.info(sb.toString());
		return sb.toString();
	}
}
